package com.ficus.road.maintain.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;

@ServerEndpoint(value = "/ws/{carId}")
@Service
@Slf4j
public class WebSocketManager extends BaseWebSocketManager {


    /**
     * 建立连接
     * 连接成功后，服务器的回调函数
     *
     * @param session session
     */
    @OnOpen
    public void onOpen(@PathParam("carId") String carId, Session session) {
        log.info("new session：{}, car:{}", session.getId(), carId);
        synchronized (sessions) {
            //todo:实时播放的时候是根据carId来存session；同一个carId可能建立多个session
            sessions.computeIfAbsent(carId, k -> new ArrayList<>()).add(session);
            increaseSession(carId, session.getId());
        }
    }


    @Override
    public void increaseSession(String carId, String sessionId) {
        log.info("WebSocketManager increaseSession");
        videoService.liveVideo(carId, sessionId);
    }

    @Override
    public void decreaseSession(String carId, String sessionId) {
        videoService.stopLiveVideo(carId, sessionId);
    }


}